<template>
  <div class="callback-container">
    <div class="callback-card">
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <p>正在处理认证...</p>
        <div class="debug-info" v-if="debugInfo">
          <p><strong>调试信息:</strong></p>
          <pre>{{ debugInfo }}</pre>
        </div>
      </div>
      <div v-else-if="error" class="error">
        <h3>认证失败</h3>
        <p>{{ error }}</p>
        <div class="debug-info" v-if="debugInfo">
          <p><strong>调试信息:</strong></p>
          <pre>{{ debugInfo }}</pre>
        </div>
        <div class="error-actions">
          <button @click="diagnoseIssue" class="diagnose-btn">诊断问题</button>
          <button @click="goToLogin" class="retry-btn">返回登录页面</button>
        </div>
      </div>
      <div v-else class="success">
        <h3>认证成功</h3>
        <p>正在跳转到主页...</p>
        <div class="debug-info" v-if="debugInfo">
          <p><strong>调试信息:</strong></p>
          <pre>{{ debugInfo }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user';
import msalService from '@/services/msalService';
import { getUserInfo } from '@/api/auth';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loading = ref(true);
const error = ref('');
const debugInfo = ref('');

onMounted(async () => {
  console.log('🔄 MS365认证成功页面开始处理');
  console.log('📍 当前URL:', window.location.href);
  console.log('📍 路由参数:', route.params);
  console.log('📍 查询参数:', route.query);
  console.log('📍 前端来源 origin:', window.location.origin);
  console.log('📍 document.cookie 原始内容:', document.cookie || '(空)');
  console.log('ℹ️ 注意：HttpOnly cookie 无法通过 document.cookie 访问');
  
  
  try {
    // 1) 优先处理：后端已完成认证（存在服务端会话/Set-Cookie）——直接拉取当前用户信息构建本地态
    try {
      console.log('🔍 尝试通过后端会话获取当前用户信息...');
      // 由于后端设置了 HttpOnly cookie，客户端无法直接读取
      // 直接调用后端 API，让 axios 自动处理 cookie
      const serverUser = await getUserInfo();
      console.log('📦 获取到的用户信息:', serverUser);
      debugInfo.value += `\n📦 获取到的用户信息: ${JSON.stringify(serverUser, null, 2)}`;
      
      if (serverUser && serverUser.id) {
        const username = serverUser.name || serverUser.login;
        userStore.setUserInfo({
          id: serverUser.id || 0,
          username,
          name: serverUser.name || username,
          email: serverUser.login || username,
          permissions: serverUser.permissions || []
        } as any);
        // 设置一个占位登录态（依赖 withCredentials + 服务端会话）
        userStore.setToken('SESSION');
        console.log('✅ 已通过后端会话构建本地登录态');
        debugInfo.value += `\n✅ 已通过后端会话构建本地登录态: ${username}`;
        // 跳转：优先 redirect，否则主页
        let redirectPath = (route.query.redirect as string) || '/';
        
        // 处理 redirect 参数可能是完整 URL 的情况
        if (redirectPath && redirectPath.startsWith('http')) {
          try {
            const url = new URL(redirectPath);
            redirectPath = url.pathname + url.search + url.hash;
            console.log('🔧 从完整URL提取路径:', redirectPath);
          } catch (e) {
            console.warn('⚠️ 无法解析redirect URL，使用默认路径:', e);
            redirectPath = '/';
          }
        }
        
        console.log('🚀 跳转:', redirectPath);
        router.replace(redirectPath);
        return;
      }
    } catch (e: any) {
      console.log('ℹ️ 后端会话获取用户信息未命中，继续后续处理', e);
      debugInfo.value += `\n❌ 获取用户信息失败: ${e.message || '未知错误'}`;
    }
    // 若上述均未命中，则报错并引导用户返回登录
    error.value = '未检测到有效登录态或授权数据，请返回登录重试';
    loading.value = false;
    
  } catch (err: any) {
    console.error('❌ 认证成功处理失败:', err);
    if (err.message) {     
      error.value = err.message || '认证过程中发生未知错误';
      debugInfo.value += `\n❌ 处理失败: ${err.message}`;
    }    
    loading.value = false;
  }
});





function goToLogin() {
  console.log('🔄 返回登录页面');
  router.push('/login');
}

function diagnoseIssue() {
  console.log('🩺 诊断按钮被点击');
  // 这里可以扩展更多诊断逻辑；为避免报错，先提供最小实现
}

</script>

<style scoped>
.callback-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
}

.callback-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  text-align: center;
  max-width: 700px;
  width: 90%;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #0d6efd;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  color: #d32f2f;
}

.error h3 {
  margin-bottom: 1rem;
}

.error-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-top: 1rem;
}

.diagnose-btn {
  background: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.diagnose-btn:hover {
  background: #f57c00;
}

.retry-btn {
  background: #0d6efd;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #0b5ed7;
}

.success {
  color: #2e7d32;
}

.success h3 {
  margin-bottom: 1rem;
}

.debug-info {
  margin-top: 1rem;
  padding: 1rem;
  background: #f5f5f5;
  border-radius: 4px;
  text-align: left;
  font-size: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.debug-info pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}
</style> 